<style lang="less">
  .ue-vehicle {
    .el-row {
      margin-bottom: 20px;
    }

    .el-col {
      border-radius: 4px;
    }

    .bg-purple-dark {
      background: #ffffff;
    }

    .grid-content {
      border-radius: 4px;
      min-height: 36px;
    }

    .el-form-item {
      margin: 0px 20px 15px 20px;
    }

    .f-bs1 {
      border: 1px solid #dfe6ec;
    }

    .el-collapse {
      border: 0px;
      .el-collapse-item {
        border: 1px solid #dfe6ec;
        margin-bottom: 10px;
        .el-collapse-item__header {
          font-weight: bold;
          .el-collapse-item__header__arrow {
            display: none;
          }
        }
        .el-collapse-item__content {
          padding-bottom: 0px;
        }
        .el-collapse-item__wrap {
          border-bottom: 0px;
        }
      }
    }

    .el-form-item[data-v-7da61f17] {
      margin: 0 0 0 0
    }

    .f-mt10 {
      margin-top: 10px;
    }

    .f-ml20 {
      margin-left: 20px;
    }

    .f-mr20 {
      margin-right: 20px;
    }

    .f-mb10 {
      margin-bottom: 10px;
    }

    .f-tar {
      text-align: right;
    }

    .f-h30 {
      height: 30px;
    }

    .f-c-red {
      color: red;
    }

    .el-radio-group {
      width: 60%;
    }

    .el-radio-invoice {
      margin-right: 30px;
    }

    .f-color {
      color: #25baaf;
    }

    .el-textarea {
      width: 86%;
    }

    .f-mb {
      margin-bottom: 0;
    }

    .f-fr {
      float: right;
    }

    .f-fl {
      float: left;
    }

    .f-lh38 {
      line-height: 38px;
    }

    .el-select {
      width: 100%;
    }

    .f-w233 {
      width: 100%;
    }

    .el-form-item__label {
      width: 150px;
    }

    .el-date-editor.el-input {
      width: 100%;
    }

    li {
      list-style-type: none;
    }

    .color-c8c8c8 {
      color: #c8c8c8;
    }

    .f-mt {
      margin-top: 0;
    }

    .width70 {
      width: 70%;
    }

    .el-transfer-panel {
      width: 415px;
    }
  }
</style>

<template>
  <section class="ue-vehicle">
    <!--工具条-->
    <search-bar more-display>
      <el-row>
        <el-col :span="8">
          <el-form-item label="车牌号码">
            <el-input  v-model="searchCondition.LIKE_plateNumber"
                      placeholder="请输入车牌号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话">
            <el-input  v-model="searchCondition.LIKE_contactPhone"
                      placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车辆归属人">
            <el-input  v-model="searchCondition.LIKE_owner"
                      placeholder="请输入车辆归属人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车辆性质">
            <el-select  v-model="searchCondition.EQ_vehicleProperty" placeholder="请选择车辆性质">
              <el-option v-for="item in $store.getters.VEHICLE_PROPERTY"
                         :key="item.dictVal"
                         :label="item.cnDictValname"
                         :value="item.dictVal"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>

    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="myReset" style="float: right">重置</el-button>
      <el-button type="primary" @click="searchBarVehicleManages" style="float: right">查询</el-button>
    </el-col>

    <!--列表-->
    <el-table :data="tableData" highlight-current-row border @sort-change="sortChange" max-height="660"
              @selection-change="selsChange" v-loading="listLoading" style="width: 100%;">
      <el-table-column type="index" label="序号" width="70" >
      </el-table-column>
      <el-table-column prop="plateNumber" label="车牌号码"  >
      </el-table-column>
      <el-table-column prop="owner" label="车辆归属人" width="130" >
      </el-table-column>
      <el-table-column prop="contactPhone" label="归属人电话" width="130" >
      </el-table-column>
      <el-table-column prop="vehicleProperty" label="车辆性质" width="130" >
        <template slot-scope="scope">
          <label v-if="scope.row.vehicleProperty === 109013001">自有车辆</label>
          <label v-if="scope.row.vehicleProperty === 109013002">合作车辆</label>
        </template>
      </el-table-column>
      <el-table-column prop="lsTypeName" label="车辆类型" width="130" >
      </el-table-column>
      <el-table-column prop="usageName" label="车辆用途" width="130" >
      </el-table-column>

      <el-table-column prop="length" label="车长(M)" width="120" >
      </el-table-column>
      <el-table-column prop="deadWeight" label="载重量(T)" width="130" >
      </el-table-column>

      <el-table-column prop="buyDate" label="购入日期" width="140" >

        <template slot-scope="scope">
          <label v-if="scope.row.buyDate != null">
            {{scope.row.buyDate.toString().substring(0, 10)}}
          </label>
        </template>

      </el-table-column>

      <el-table-column prop="licensingDate" label="上牌日期" width="140" >

        <template slot-scope="scope">
          <label v-if="scope.row.licensingDate != null">
            {{scope.row.licensingDate.toString().substring(0, 10)}}
          </label>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250">
        <template slot-scope="scope">

          <el-button  type="primary" @click="getEditBYId(scope.$index, scope.row)">编辑 </el-button>
          <el-button type="danger"  @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary"  @click="assignDriver(scope.$index, scope.row)">指定司机
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>

    <!--新增车辆 弹窗 -->
    <el-dialog :title="dialogTitle" size="large" :visible.sync="VehicleVisible" :close-on-click-modal="false">
      <el-form :model="vehicleInfo" :rules="rules" label-width="80px" ref="vehicleInfo">
        <el-row class="f-mt10 f-mb10">
          <el-col :span="8">
            <el-form-item class="width70" label="车牌号" prop="plateNumber">
              <el-input v-model="vehicleInfo.plateNumber" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆性质"  prop="vehicleProperty" class="width70">
              <el-select  v-model="vehicleInfo.vehicleProperty" placeholder="请选择车辆性质">
                <el-option v-for="item in $store.getters.VEHICLE_PROPERTY"
                           :key="item.dictVal"
                           :label="item.cnDictValname"
                           :value="item.dictVal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="隶属机构" class="width70">
              <el-cascader style="width: 100%"
                placeholder="请选择隶属机构"
                :options="$store.state.initOrganizations"
                :props="{label: 'name',value: 'id'}"
                change-on-select
                v-model="currentOrganizationIds"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="width70" label="车主" prop="owner">
              <el-input v-model="vehicleInfo.owner" placeholder="请输入车主/单位"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="车辆类型" prop="type">
              <el-select  v-model="vehicleInfo.type"
                         placeholder="请选择">
                <el-option
                  v-for="item in $store.getters.TRUCK_TYPE"
                  :key="item.dictVal"
                  :label="item.cnDictValname"
                  :value="item.dictVal">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="联系人" prop="contactPerson">
              <el-input v-model="vehicleInfo.contactPerson" placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="车辆用途" prop="usage">
              <el-select  v-model="vehicleInfo.usage"
                         placeholder="请选择">
                <el-option
                  v-for="item in $store.getters.VEHICLE_USAGE"
                  :key="item.dictVal"
                  :label="item.cnDictValname"
                  :value="item.dictVal">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="width70" label="车长(M)" prop="length">
              <el-input type="number" v-model.number="vehicleInfo.length" placeholder="请输入车长"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="行驶证号" prop="drivingNumber">
              <el-input v-model="vehicleInfo.drivingNumber" placeholder="请输入行驶证号"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="联系电话" prop="contactPhone">
              <el-input v-model="vehicleInfo.contactPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="width70" label="载重(T)" prop="deadWeight">
              <el-input type="number" v-model.number="vehicleInfo.deadWeight" placeholder="请输入载重量"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="车架号" prop="frameNumber">
              <el-input v-model="vehicleInfo.frameNumber" placeholder="请输入车架号"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="width70" label="发动机号" prop="engineNumber">
              <el-input v-model="vehicleInfo.engineNumber" placeholder="请输入发动机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="width70" label="购入日期" prop="buyDate">
              <el-date-picker
                v-model="vehicleInfo.buyDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="width70" label="上牌日期" prop="licensingDate">
              <el-date-picker
                v-model="vehicleInfo.licensingDate"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="VehicleVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading1">提交</el-button>
      </div>
    </el-dialog>

    <!--指定司机 弹窗 -->
    <el-dialog class="assign-driver" :title="assignTitle"  :visible.sync="assignVisible"
               :close-on-click-modal="false">
      <el-form :model="vehicleInfo" :rules="rules" label-width="80px" ref="vehicleInfo">
        <el-transfer
          :titles="['待指定司机列表', '指定司机列表']"
          filterable
          :button-texts="['返回', '指定']"
          :props="{key: 'value',label: 'desc'}"
          filter-placeholder="请输入司机姓名"
          v-model="assignDriverList"
          :data="driverInfoData">
        </el-transfer>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="assignVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveDriver" :loading="submitLoading1">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import {
  saveVehicleInfo,
  searchVehicleInfo,
  getVehicleInfo,
  delVehicle,
  saveDriverInfoAndVehicle
} from '../../api/stowage/VehicleManage';
import {getOrganizationById} from '../../api/organization/Organization';
import {objToFilter, resetObjNull, isEmpty} from '../../lib/util';

import {
  searchDriverInfo
} from '../../api/stowage/DriverManage';

export default {
  data () {
    return {
      currentVehicleId: '',
      assignDriverList: [],
      currentOrganizationIds: [],
      driverInfoData: [],

      searchCondition: {
        LIKE_plateNumber: null,
        LIKE_contactPhone: null,
        LIKE_owner: null,
        EQ_vehicleProperty: null
      },

      props1: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      stowageCoreCenter: [],
      stowageCoreCenter2: [],

      sels: [],
      types: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      listLoading: false,
      VehicleVisible: false,
      assignVisible: false,
      submitLoading: false,
      submitLoading1: false,

      dialogTitle: '新增',
      condition: {
        name: '',
        number: ''
      },

      assignTitle: '指定司机',

      // 表单数据
      vehicleInfo: {
        'id': null,
        'usage': null,
        'vehicleOrganizationId': null,
        'plateNumber': null,
        'owner': null,
        'type': null,
        'typeEntity': null,
        'contactPhone': null,
        'contactPerson': null,
        'drivingNumber': null,
        'length': null,
        'deadWeight': null,
        'buyDate': null,
        'licensingDate': null,
        'organizationId': null,
        'frameNumber': null,
        'engineNumber': null,
        'operationLicenseUrl': null,
        'drivingLicenseUrl': null,
        'imgUrl': null,
        'vehicleProperty': null
      },

      // 验证规则
      rules: {
        plateNumber: [
          {required: true, message: '请输入车牌号', trigger: 'blur'},
          {min: 7, max: 7, message: '长度在7个字符', trigger: 'blur'}
        ],
        owner: [
          {required: true, message: '请输入车主/单位', trigger: 'blur'},
          {min: 2, max: 60, message: '长度在2到 60 个字符', trigger: 'blur'}
        ],
        contactPerson: [
          {required: true, message: '请输入联系人', trigger: 'blur'},
          {min: 2, max: 60, message: '长度在2到 60 个字符', trigger: 'blur'}
        ],
        length: [
          {type: 'number', required: true, message: '请输入车长', trigger: 'blur'}
        ],
        type: [
          {type: 'number', required: true, message: '请选择车辆类型', trigger: 'change'}
        ],
        vehicleProperty: [
          {type: 'number', required: true, message: '请选择车辆性质', trigger: 'change'}
        ],
        usage: [
          {type: 'number', required: true, message: '请选择车辆用途', trigger: 'change'}
        ],
        drivingNumber: [
          {required: true, message: '请输入行驶证号', trigger: 'blur'}
          // {min: 18, max: 18, message: '长度在18个字符', trigger: 'blur'}
        ],
        deadWeight: [
          {type: 'number', required: true, message: '请输入载重量', trigger: 'blur'}
        ],
        buyDate: [
          {type: 'date', required: true, message: '请选择购入日期', trigger: 'blur'}
        ],
        licensingDate: [
          {type: 'date', required: true, message: '请选择上牌日期', trigger: 'blur'}
        ],
        frameNumber: [
          {required: true, message: '请输入车架号', trigger: 'blur'},
          {min: 17, max: 17, message: '长度在17个字符', trigger: 'blur'}
        ],
        engineNumber: [
          {required: true, message: '请输入发动机号', trigger: 'blur'}
          // {min: 10, max: 10, message: '长度在10个字符', trigger: 'blur'}
        ],
        contactPhone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '长度在11个字符', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    // 保存指定司机
    saveDriver () {
      saveDriverInfoAndVehicle(this.currentVehicleId, this.assignDriverList).then((res) => {
        if (res.status === 200) {
          this.searchBarVehicleManages();
          this.$message('指定成功');
          this.assignVisible = false;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },

    // 打开指定司机窗口
    assignDriver (index, row) {
      searchDriverInfo({
        filters: 'ISNULL_LEFT_relations.vehicleInfo',
        sorts: '',
        page: 0,
        size: 10000
      }).then((res) => {
        if (res.status === 200) {
          this.driverInfoData = res.data.concat(row.driverInfos).map(item => {
            return {value: item.id, desc: '姓名:' + item.name + ',手机:' + item.phone};
          });
          this.assignTitle = '指定司机';
          this.currentVehicleId = row.id;
          this.assignDriverList = row.driverInfos.map(item => item.id);
          this.assignVisible = true;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    // 删除单条数据操作
    handleDel (index, row) {
      this.$confirm('确认删除该车辆吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        delVehicle(row.id).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.searchBarVehicleManages();
        });
      }).catch(() => {
      });
    },
    // 搜索 栏重置
    myReset () {
      resetObjNull(this.searchCondition);
      this.createsDaterange = [];
    },
    loadingLists (filter) {
      this.listLoading = true;
      searchVehicleInfo({
        filters: filter,
        sort: 'createdDate,desc',
        page: this.currentPage - 1,
        size: this.pageSize
      }).then(res => {
        if (res.status === 200) {
          this.tableData = res.data;
          this.total = Number(res.headers['x-total-count']);
          this.listLoading = false;
        }
      });
    },

    // 搜索
    searchBarVehicleManages () {
      this.loadingLists(objToFilter(this.searchCondition));
    },

    // 打开编辑界面
    getEditBYId (index, row) {
      this.currentOrganizationIds = [];
      this.resetForm();
      // this.vehicleInfo = Object.assign({}, row);
      getVehicleInfo(row.id).then((res) => {
        if (res.status === 200) {
          this.vehicleInfo = res.data;
          this.currentOrganizationIds = res.data.vehicleOrganiaztionId.split(',');
        }
      });
      this.currentOrganizationIds = Object.assign([], this.currentOrganizationIds);
      this.dialogTitle = '修改';
      this.VehicleVisible = true;
    },

    // 新增数据提交
    handleSubmit () {
      // 表单验证
      if (!isEmpty(this.vehicleInfo.buyDate)) {
        this.vehicleInfo.buyDate = new Date(this.vehicleInfo.buyDate);
      }
      if (!isEmpty(this.vehicleInfo.licensingDate)) {
        this.vehicleInfo.licensingDate = new Date(this.vehicleInfo.licensingDate);
      }
      this.$refs['vehicleInfo'].validate((valid) => {
        if (valid) {
          this.vehicleInfo.vehicleOrganizationId = this.currentOrganizationIds.join(',');
          if (this.vehicleInfo.buyDate > this.vehicleInfo.licensingDate) {
            return this.$message.error('购入日期不能大于上牌日期');
          }
          ;
          this.submitLoading = true;
          saveVehicleInfo(this.vehicleInfo).then((res) => {
            this.submitLoading = false;
            if (res.status === 201) {
              this.VehicleVisible = false;
              this.$message.success('保存/修改成功！');
              this.searchBarVehicleManages();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },
    // 弹出添加窗体
    handleAdd () {
      this.dialogTitle = '新增';
      this.resetForm();
      this.currentOrganizationIds = [];
      this.VehicleVisible = true;
    },

    // 重置表单
    resetForm () {
      if (this.$refs.vehicleInfo) {
        this.$refs.vehicleInfo.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.vehicleInfo) {
        if (this.vehicleInfo[p] instanceof Array) {
          this.vehicleInfo[p] = [];
        } else {
          this.vehicleInfo[p] = null;
        }
      }
    },

    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchBarVehicleManages();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchBarVehicleManages();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchBarVehicleManages();
    },

    // 表格数据
    getTableData () {
      let str = [];
      for (let p in this.condition) {
        if (this.condition[p] !== '' && this.condition[p] !== null) {
          str.push(p + '=' + this.condition[p]);
        }
      }
      this.listLoading = true;
      searchVehicleInfo({
        filters: '',
        sorts: '',
        page: this.currentPage,
        size: this.pageSize
      }).then((res) => {
        if (res.data.successFlg === true) {
          this.tableData = res.data.detailModelList;
          this.total = res.data.totalCount;
          this.listLoading = false;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    }
  },

  mounted () {
    getOrganizationById(this.$store.state.currentOrganizationId).then(res => {
      if (res.data.successFlg) {
        if (res.data.obj) {
          let ids = Object.assign([], res.data.obj.pids);
          ids.push(res.data.obj.id);
          this.currentOrganizationIds = Object.assign([], ids);
        } else {
          this.currentOrganizationIds = [];
        }
      }
    });
    this.searchBarVehicleManages();
    this.$store.commit('initDict');
    this.$store.commit('initOrganizations');
  }
};
</script>
